API Gateway
An API Gateway is a critical component in system design, particularly in microservices architecture. It acts as a single entry point for all client requests and routes them to the appropriate backend services.
Features of API Gateway
| Feature | Purpose |
|---|---|
| Routing | Request goes to the right microservice |
| Auth | Verifies user credentials (e.g., JWT) |
| Rate Limiting | Protects backend from overload |
| Caching | Reduces load, speeds up repeated queries |
| Load Balancing | Distributes traffic across instances |
| Monitoring | Logs metrics for observability |
Why Use an API Gateway?
In microservices, services are often broken into small units (e.g., auth, order, payment, etc.). If clients (like mobile apps or browsers) directly interact with all these, it:
- Increases complexity
- Exposes internal service structure
- Requires handling cross-cutting concerns multiple times
An API Gateway abstracts these concerns and centralizes them.
API Gateway Worflow
Let’s say you’re designing an e-commerce system:
Services:
User Service(/users)Product Service(/products)Order Service(/orders)
Client Flow:
- The client sends a request to
/api/products. - The API Gateway receives the request.
- It authenticates the user (via token).
- It routes the request to the
Product Service. - The response comes back to the gateway.
- The gateway may transform the response.
- The client gets the response.
Example of API Gateway
// api-gateway.js
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const app = express();
// Middleware: Log all requests
app.use((req, res, next) => {
console.log(`[Gateway] ${req.method} ${req.originalUrl}`);
next();
});
// Forward /users requests
app.use(
"/users",
createProxyMiddleware({
target: "http://localhost:5001", // User Service
changeOrigin: true,
})
);
// Forward /products requests
app.use(
"/products",
createProxyMiddleware({
target: "http://localhost:5002", // Product Service
changeOrigin: true,
})
);
// Forward /orders requests
app.use(
"/orders",
createProxyMiddleware({
target: "http://localhost:5003", // Order Service
changeOrigin: true,
})
);
app.listen(3000, () => {
console.log("API Gateway running on port 3000");
});
Benefits and Trade-offs of API Gateway
| Benefits | Trade-offs |
|---|---|
| Simplifies client interaction | Single point of failure (if not replicated) |
| Centralizes security and logging | Adds latency (extra network hop) |
| Enables decoupled service development | Can become complex (requires scaling & config management) |
| Supports versioning, throttling, caching |